/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.distribution.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.distribution.api.param.DistributionWithdrawCashSaceParam;
import com.yami.shop.distribution.common.constants.DistributionUserStateEnum;
import com.yami.shop.distribution.common.dto.DistributionWithdrawCashDto;
import com.yami.shop.distribution.common.dto.DistributionWithdrawCashSetDto;
import com.yami.shop.distribution.common.model.DistributionUser;
import com.yami.shop.distribution.common.param.RangeTimeParam;
import com.yami.shop.distribution.common.service.DistributionUserService;
import com.yami.shop.distribution.common.service.DistributionUserWalletService;
import com.yami.shop.distribution.common.service.DistributionWithdrawCashService;
import com.yami.shop.distribution.common.vo.DistributionConfigVO;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.security.common.enums.SocialType;
import com.yami.shop.security.common.model.AppConnect;
import com.yami.shop.security.common.service.AppConnectService;
import com.yami.shop.service.SysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

/**
 * @author yami
 */
@RestController
@RequestMapping("/p/distribution/withdrawCash")
@Api(tags = "分销员提现接口")
public class DistributionWithdrawCashController {
    @Autowired
    private DistributionWithdrawCashService distributionWithdrawCashService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private DistributionUserService distributionUserService;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private DistributionUserWalletService distributionUserWalletService;
    @Autowired
    private AppConnectService appConnectService;

    @GetMapping("/info")
    @ApiOperation(value = "获取提现设置信息")
    public ServerResponseEntity<DistributionWithdrawCashSetDto> setInfo() {
        DistributionConfigVO distributionConfigVO = sysConfigService.getSysConfigObject(Constant.DISTRIBUTION_CONFIG, DistributionConfigVO.class);
        return ServerResponseEntity.success(mapperFacade.map(distributionConfigVO, DistributionWithdrawCashSetDto.class));
    }

    @GetMapping("/page")
    @ApiOperation(value = "分页查看提现记录")
    public ServerResponseEntity<IPage<DistributionWithdrawCashDto>> page(PageParam<DistributionWithdrawCashDto> page) {
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(SecurityUtils.getUser().getUserId(), Constant.PLATFORM_SHOP_ID);
        if (Objects.isNull(distributionUser)) {
            // 您还不是分销员
            throw new YamiShopBindException("yami.distribution.user.no.distributor");
        }
        return ServerResponseEntity.success(distributionWithdrawCashService.distributionWithdrawCashDtoPageByUserId(page, distributionUser.getDistributionUserId()));
    }

    @PostMapping("/apply")
    @ApiOperation(value = "用户发起提现申请", notes = "填入提现参数")
    public ServerResponseEntity<Void> apply(@Valid @RequestBody DistributionWithdrawCashSaceParam distributionWithdrawCashSaceParam) {
        String userId = SecurityUtils.getUser().getUserId();
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(userId, Constant.PLATFORM_SHOP_ID);
        if (Objects.isNull(distributionUser)) {
            // 您还不是分销员
            throw new YamiShopBindException("yami.distribution.user.no.distributor");
        }
        if (!Objects.equals(distributionUser.getState(), DistributionUserStateEnum.NORMAL.getValue())){
            // 您的分销身份异常，请联系管理员
            throw new YamiShopBindException("yami.distribution.user.no.distributor1");
        }
        AppConnect appConnect = appConnectService.getOne(new LambdaQueryWrapper<AppConnect>()
                .eq(AppConnect::getUserId, distributionUser.getUserId())
                .eq(AppConnect::getAppId, SocialType.MA.value()));
        if(Objects.isNull(appConnect)){
            throw new YamiShopBindException("yami.distribution.user.withdrawals");
        }
        //发起提现
        distributionWithdrawCashService.apply(distributionWithdrawCashSaceParam.getAmount(), distributionUser, appConnect);
        return ServerResponseEntity.success();
    }

    @GetMapping("/isWithdrawCash")
    @ApiOperation(value = "当前是否可以提现")
    public ServerResponseEntity<Boolean> isWithdrawCash() {
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(SecurityUtils.getUser().getUserId(), Constant.PLATFORM_SHOP_ID);
        Long distributionUserId = distributionUser.getDistributionUserId();
        //获取店铺提现设置
        DistributionConfigVO distributionWithdrawCashSet = sysConfigService.getSysConfigObject(Constant.DISTRIBUTION_CONFIG, DistributionConfigVO.class);
        //获取店铺设置的提现频率算出时间区间
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - distributionWithdrawCashSet.getFrequency());
        //获取玩家最近的提现次数
        //判断是否能够提现
        if (distributionWithdrawCashService.getCountByRangeTimeAndDistributionUserId(new RangeTimeParam(calendar.getTime(), new Date()), distributionUserId) >= distributionWithdrawCashSet.getNumber()) {
            // 提现次数为x天x次
            String info = I18nMessage.getMessage("yami.distribution.cash.num");
            String num = I18nMessage.getMessage("yami.constant.num");
            String day = I18nMessage.getMessage("yami.day");
            throw new YamiShopBindException(info + distributionWithdrawCashSet.getFrequency() + day + distributionWithdrawCashSet.getNumber() + num);
        }
        return ServerResponseEntity.success(true);
    }

    @GetMapping("/totalWithdrawCash")
    @ApiOperation(value = "查看用户总提现金额")
    public ServerResponseEntity<Double> getUserTotalWithdrawCash() {
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(SecurityUtils.getUser().getUserId(), Constant.PLATFORM_SHOP_ID);
        if (Objects.isNull(distributionUser)) {
            // 您还不是分销员
            throw new YamiShopBindException("yami.distribution.user.no.distributor");
        }
        Long distributionUserId = distributionUser.getDistributionUserId();
        Long walletId = distributionUserWalletService.getWalletIdByDistributionUserId(distributionUserId);
        Double totalWithdrawCash = distributionWithdrawCashService.getUserTotalWithdrawCash(walletId);
        return ServerResponseEntity.success(totalWithdrawCash);
    }
}
